package com.bd.scm.module.qywx.controller;

import com.alibaba.fastjson.JSONObject;
import com.bd.scm.module.common.BaseController;
import com.bd.scm.module.qywx.service.SysUserService;
import com.bd.scm.module.qywx.thread.TokenThread;
import com.bd.scm.module.utils.qywx.GOauth2Core;
import com.bd.scm.module.utils.qywx.WeiXinParamesUtil;
import com.bd.utils.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/qywx")
public class SysUserController  extends BaseController {

	private static Logger log = LoggerFactory.getLogger(SysUserController.class);

	@Autowired
	private SysUserService sysUserService;

	//平台
	@GetMapping("login")
	public Result login(HttpServletRequest request){
		Result result = null;
		try {
			JSONObject map  = new JSONObject();
			HttpSession session = request.getSession();
			String UserID="";
			if(session.getAttribute("user")==null||session.getAttribute("user")==""){
				String code = request.getParameter("code");
				if (!"authdeny".equals(code)) {
					String access_token = TokenThread.accessToken.getToken();
					// agentid 跳转链接时所在的企业应用ID 管理员须拥有agent的使用权限；agentid必须和跳转链接时所在的企业应用ID相同
					try {
						UserID = GOauth2Core.GetUserID(access_token, code, WeiXinParamesUtil.getProperty("agentId"));
					} catch (Exception e) {
						log.info(e.getMessage());
						//new TokenThread().doBusiness();
					}
				}
			}else {
				map = (JSONObject) session.getAttribute("user");
				UserID = map.getString("account");
				map = sysUserService.selectDtuser(UserID);
			}
			if(!"".equals(UserID)) {
				map = sysUserService.selectDtuser(UserID);
				session.setAttribute("user", map);
			}
			result = Result.ok(map);
		} catch (Exception e) {
			e.printStackTrace();
			result = Result.error("程序内部错误");
		}
		return result;
	}

//	public synchronized ModelAndView logic(String UserID, JSONObject jsonObject, String URL) {
//
//			if("".equals(UserID)) {
//				return new ModelAndView("phone_close")
//						.addObject("message", "微信账号不匹配")
//						.addObject("UserID", UserID);
//			}
//
//			if(null==jsonObject) {
//				return new ModelAndView("phone_close")
//						.addObject("message", "该人员不存在")
//						.addObject("UserID", UserID);
//			}
//		return new ModelAndView(URL);
//	}
}
